package wqlbatisplus.batispluswql.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wqlbatisplus.batispluswql.cv.Result;
import wqlbatisplus.batispluswql.dao.UserDao;
import wqlbatisplus.batispluswql.entity.User;
import wqlbatisplus.batispluswql.service.UserService;
import wqlbatisplus.batispluswql.util.JwtUtil;

import java.util.HashMap;
import java.util.List;

/**
 * @author wql
 * @version 1.0
 * @date 2022/11/19 15:55
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public Result findByPage(int currentPage, int pageSize) {
        Page<User> page = new Page<>(currentPage,pageSize);
        Page<User> userPage = userDao.selectPage(page, null);
        return new Result(200,"查询成功",userPage);
    }

    @Override
    public Result deleteById(Integer id) {
        userDao.deleteById(id);
        return new Result(200,"删除成功");
    }

    @Override
    public Result update(User user) {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",user.getId());
        userDao.update(user,wrapper);
        return new Result(200,"修改成功");
    }

    @Override
    public Result login(String username, String password) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username" , username);
        wrapper.eq("password" ,password);
        User user = userDao.selectOne(wrapper);
        if (user!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("username" ,username);
            map.put("password",password);
            String token = JwtUtil.createToken(map);
            return new Result(200,"登录成功",token);
        }else {
            return new Result(500,"登陆失败");
        }
    }

    @Override
    public Result addUser(User user) {
        userDao.insert(user);
        return new Result(200,"添加成功");
    }
}
